qui(
    function (require, exports, module) {
        WrapSys.CornerManager = (function () {
            var entityIdIndex = 1;
            var cornPicIdIndex = 1;
            var cornerLabel = '<label onclick="$(this).remove();$(\'#corner_hoverTip\').hide()" corn-key="true" style="position: absolute;top: 0px;left: 0px;text-align: center;width: 100%;color: #ffffff;background-color: brown">贴片入点</label>';
            var cornerEndLabel = '<label onclick="$(this).remove();" corn-end-key="true" style="position: absolute;top: 0px;left: 0px;text-align: center;width: 100%;color: #ffffff;background-color: brown">贴片出点</label>';
            var hasBindEvent = false;
            var _options = {};
            var maxLineWidth = 260;
            var operator = {
                add: function () {
                    $("label[corn-key]").click();
                    $("label[corn-end-key]").click();
                    var entity = createEntity();
                    getPageBean().addNewOne(entity);
                    updateEntity();
                    $("#material_list").jqGrid('setSelection', entity.index);
                    //   WrapSys.Util.setMaskHighLight(null);
                },
                del: function (rowId) {
                    var findData = getPageBean().findData("index", rowId);
                    if (findData != null) {
                        var handler = function () {
                            getPageBean().delOne(findData);
                            updateEntity();
                            $("label[corn-key]").click();
                            $("label[corn-end-key]").click();
                        }
                        if (findData.range.length == 0) {
                            SystemDialog.queryConfirm("确认删除么?", function (flag) {
                                if (flag == true) {
                                    handler();
                                }
                            })
                        } else {
                            checkNeedRemind("del", findData, function () {
                                WrapSys.Util.dataChangeRemindCheck(findData, handler)
                            })
                        }
                    }
                },
                clear: function () {
                    var source = getPageBean().getSource();
                    if (source.length > 0) {
                        var handler = function () {
                            getPageBean().setNewData([]);
                            updateEntity();
                            setHighLight(null);
                        }
                        var hasReadyToSend = false;
                        $.each(source, function (i, element) {
                            if (element.readyToSend == true) {
                                hasReadyToSend = true;
                            }
                        })
                        WrapSys.Util.dataChangeRemindCheck({readyToSend: hasReadyToSend }, handler)
                    }
                }
            }

            function addCornPic(original) {
                var value = validCheck();
                var entity = getSelectEntity();
                if ((entity.eTime != -1 && entity.eTime < value ) || entity.sTime == -1 || entity.sTime > value) {
                    WrapSys.Plugin.tips("error", WrapSys.Config.REMIND_MSG_INFO.INVALID_CORNER_INFO);
                    return;
                }
                var picEntity = createCornerPic(original)
                entity.bindArr.push(picEntity);
                updateGridColMaterialName(entity);
            }

            function updateGridColMaterialName(entity) {
                if (entity.bindArr.length == 0) {
                    entity.materialName = "";
                } else if (entity.bindArr.length == 1) {
                    entity.materialName = entity.bindArr[0].name;
                } else {
                    entity.materialName = entity.bindArr[0].name + " 等";
                }
                notifyUpdateCornerGrid(entity)
            }

            function createCornerPic(original) {
                var picEntity = {
                    id: cornPicIdIndex,
                    materialId: original.id,
                    url: original.url,
                    name: original.name,
                    contentType: original.contentType
                }
                cornPicIdIndex++;
                return picEntity
            }

            function createEntity(original) {
                var cornerEntity = {
                    index: entityIdIndex,
                    sTime: -1,
                    range: [],
                    eTime: -1,
                    materialName: "",
                    bindArr: []
                }
                entityIdIndex++;
                return cornerEntity
            }

            function recordStart(value, skipCheck) {
                skipCheck = skipCheck == true ? true : false;
                console.log("recordStart start")
                if (!hasBindEvent) {
                    bindCornerLabelHoverHandler();
                }
                var entity = getSelectEntity();
                if (entity == null) {
                    WrapSys.Plugin.tips("error", WrapSys.Config.REMIND_MSG_INFO.NOT_BIND_CORNER);
                    return;
                }
                var newstart = value == null ? validCheck() : value;
                if (!skipCheck) {
                    if (entity.eTime != -1 && ( entity.eTime <= newstart || entity.sTime == newstart)) {
                        return;
                    }
                }

                entity.sTime = newstart;
                updateViewStart(entity);

            }


            function recordEnd(value, skipCheck) {
                skipCheck = skipCheck == true ? true : false;
                console.log("recordEnd start")
                var entity = getSelectEntity();
                if (entity == null) {
                    WrapSys.Plugin.tips("error", WrapSys.Config.REMIND_MSG_INFO.NOT_BIND_CORNER);
                    return;
                }
                var newEnd = value == null ? validCheck() : value;
                if (!skipCheck) {
                    if (entity.eTime == newEnd || entity.sTime >= newEnd) {
                        return;
                    }
                }

                entity.eTime = newEnd;
                updateViewEnd(entity);
            }

            function updateViewStart(entity) {
                $("label[corn-key]").remove();
                var corner = $(cornerLabel);
                corner.attr('corner-id', entity.index);
                $("#img-" + entity.sTime).parent().append(corner);
                console.log("recordStart end");
                notifyUpdateCornerGrid(entity);
            }

            function updateViewEnd(entity) {
                $("label[corn-end-key]").remove();
                $("#img-" + entity.eTime).parent().append(cornerEndLabel);
                notifyUpdateCornerGrid(entity);
            }

            function notifyUpdateCornerGrid(object) {
                $('#material_list').setRowData(object.index, object);
            }

            function bindCornerLabelHoverHandler() {
                $("#makedImg").delegate("label[corn-key]", "mouseover", hoverHandler);
                $("#makedImg").delegate("label[corn-key]", "mouseout", hoverEndHandler);
                hasBindEvent = true;
            }

            function accountLineCount(titleLength) {
                var tempWidth = titleLength * 7 + 15;
                return  Math.ceil(tempWidth / maxLineWidth)
            }

            function hoverHandler(event) {
                var currentTarget = $(event.currentTarget);
                var cornerId = parseInt(currentTarget.attr("corner-id"));
                var entity = getPageBean().findData("index", cornerId);
                var lineCount = 1;
                var lineWidth = 120;

                if (entity.bindArr.length == 0) {
                    $("#corner_hoverTip").find("div.popover-content-corner").html("没有绑定素材");
                } else {
                    // lineCount = entity.bindArr.length;
                    var htmlArr = [];
                    var maxWidthLength = -1;
                    lineCount = 0;
                    $.each(entity.bindArr, function (i, element) {
                        htmlArr.push("[" + element.id + "]" + element.name + "," + element.contentType);
                        if (maxWidthLength < htmlArr[i].length) {
                            maxWidthLength = htmlArr[i].length
                        }
                        lineCount += accountLineCount(htmlArr[i].length);
                    })
                    lineWidth = maxWidthLength * 7 + 15
                    $("#corner_hoverTip").find("div.popover-content-corner").html(htmlArr.join("<br>"));
                }
                if (lineWidth > maxLineWidth) {
                    lineWidth = maxLineWidth;
                }
                $("#corner_hoverTip").css({height: 20 * lineCount, width: lineWidth });
                $("#corner_hoverTip").css({
                    left: currentTarget.offset().left - $("#corner_hoverTip").width(),
                    top: currentTarget.offset().top
                });
                $("#corner_hoverTip").show();
            }

            function hoverEndHandler(event) {
                $("#corner_hoverTip").hide();
            }

            function validCheck() {
                return parseInt($(".red").parent().find(".pid").html());
            }

            function getSelectEntity() {
                var selRow = $("#material_list").jqGrid("getGridParam", "selrow");
                if (selRow == null) {
                    return null;
                }
                return  getPageBean().findData("index", parseInt(selRow));
            }

            function getEntity(sourceId) {
                var entity = getPageBean().findData("index", sourceId);
                return entity;
            }

            function getSource() {
                return WrapSys.Config.PageBeanCorner.getSource();
            }

            function getPageBean() {
                return  WrapSys.Config.PageBeanCorner;
            }

            function updateEntity() {
                WrapSys.Util.updateGridCornerEntity();
            }

            function openEditCornerDlg(from_path, skipCheck) {
                skipCheck = skipCheck == true ? true : false;
                var selRow = $("#material_list").jqGrid("getGridParam", "selrow");
                if (selRow == null) {
                    return null;
                }
                var entity = getPageBean().findData("index", parseInt(selRow));
                if (entity.sTime == -1) {
                    WrapSys.Plugin.tips("error", WrapSys.Config.REMIND_MSG_INFO.BIND_CORNER_START_FIRST);
                    return;
                }
                if (!skipCheck) {
                    checkNeedRemind("modify", entity, function () {
                        openEditCornerDlg(from_path, true);
                    })
                    return;
                }
                var imageId = -1;
                if (from_path == "from_keyCode") {
                    if ($(".red").length > 0) {
                        imageId = parseInt($(".red").parent().find(".pid").html());
                        if (entity.sTime > imageId || ( entity.eTime != -1 && imageId > entity.eTime  )) {
                            return
                        }
                    }
                } else {
                    imageId = entity.sTime
                }
                if (imageId < 0) {
                    console.log("openEditCornerDlg error image id ", imageId)
                    return;
                }
                $("#navCornerDiv").tabs({active: 0});
                $("#cornerImgDiv").html("")
                var paramsData = WrapSys.Dao.getParamsData();
                var data = {
                    image_id: imageId,
                    channel_code: paramsData.channel_name,
                    from_client: true,
                    key: WrapSys.Dao.settings.taskid
                };
                WrapSys.DynamicDiv.initDynamicPanel("corner_image_div");
                WrapSys.Dao.getOcrImage(data, function (rdata) {
                    if (rdata != null && rdata.code == "A00000") {
                        var tempHandler = function (rdata2) {
                            if (rdata2 != null && rdata2.code == "A00000") {
                                // _options.imageTarget.attr("src", rdata.uri)
                                WrapSys.DynamicDiv.loadBg(rdata2.uri, function () {
                                    readCornerObjPos(entity);
                                });
                                console.log(" openEditCornerDlg suc");
                                $("#edit_corner-dlg").dialog("open")
                            } else {
                                WrapSys.Plugin.tips("error", WrapSys.Config.REMIND_MSG_INFO.GET_IMG_FAIL);
                                WrapSys.Util.logSubmit(WrapSys.Config.VOD_LOG_TYPE.getImageData, data, {error: WrapSys.Config.REMIND_MSG_INFO.GET_IMG_FAIL}, WrapSys.Dao.getDotData().findImage);
                                WrapSys.Util.notifyAlert(WrapSys.Config.REMIND_MSG_INFO.GET_IMG_FAIL + ";" + WrapSys.Dao.getDotData().findImage + "|" + JSON.stringify(data).replace(/"/g, ""));
                            }
                        }
                        if (WrapSys.Config.READ_IMAGE_METHOD == "new") {
                            WrapSys.Dao.doFindImage("corner_image", data, tempHandler)
                        } else {
                            tempHandler(rdata);
                        }
                    } else {
                        WrapSys.Plugin.tips("error", "请求图片失败!");
                    }
                });
            }

            function initEditCornerDlg() {
                $("#edit_corner-dlg").dialog({
                    title: "特效素材贴片位置",
                    resizable: false,
                    dialogClass: 'alert',
                    autoOpen: false,
                    width: 1120,
                    modal: true,
                    close: function () {
                        WrapSys.DynamicDiv.destroy();
                    }
                })
                bindOptions({
                    gridTarget: $("#material_list"),
                    dlgTarget: $("#edit_corner-dlg"),
                    btn_preview: $("button[name=image_corner-preview]"),
                    btn_ok: $("button[name=image_corner-ok]"),
                    btn_cancel: $("button[name=image_corner-cancel]")
                })
                $("#navCornerDiv").tabs();

            }

            function bindOptions(options) {
                _options = options;
                _options.btn_ok.on("click", function (e) {
                    recordCornerObjPos()
                    _options.dlgTarget.dialog("close");
                })
                _options.btn_cancel.on("click", function (e) {
                    _options.dlgTarget.dialog("close");
                });
                _options.btn_preview.on("click", function (e) {
                    doCornerPreview();
                });
            }

            function recordCornerObjPos() {
                var selRow = $("#material_list").jqGrid("getGridParam", "selrow");
                var entity = getPageBean().findData("index", parseInt(selRow));
                console.log("wait to do recordCornerObjPos")
                var arrayObj = WrapSys.DynamicDiv.getMaterials();
                var newArr = [];
                var tmp = null;
                $.each(entity.bindArr, function (i, element) {
                    tmp = arrayObj["key_" + element.id];
                    if (tmp != null) {
                        element.x = tmp.x;
                        element.y = tmp.y;
                        element.w = tmp.w;
                        element.h = tmp.h;
                        element.ratio = tmp.ratio;
                        newArr.push(element);
                    }
                })
                var needUpdateGrid = newArr.length < entity.bindArr.length;
                entity.bindArr = newArr;
                if (needUpdateGrid) {
                    updateGridColMaterialName(entity)
                }
            }

            function readCornerObjPos() {
                var selRow = $("#material_list").jqGrid("getGridParam", "selrow");
                var entity = getPageBean().findData("index", parseInt(selRow))
                console.log("wait to do recordCornerObjPos")
                if (entity.bindArr != null) {
                    $.each(entity.bindArr, function (i, element) {
                        var elmStyle = {center: true};
                        if (element.x != null) {
                            elmStyle.x = element.x;
                            elmStyle.y = element.y;
                            elmStyle.w = element.w;
                            elmStyle.h = element.h;
                            elmStyle.center = false;
                        }
                        WrapSys.DynamicDiv.addImg(element.id, element.url, elmStyle);
                    })
                }
            }

            function doCornerPreview() {
                $("#navCornerDiv").tabs({active: 1});
                $("#cornerImgDiv").html("");
                $("#cornerImgDiv").css({width: 900, height: 600})
                var bgImgUrl = WrapSys.DynamicDiv.getConfig().baseDiv.find("img[name=panel-bg]").attr("src");
                var imgBg = $('<img onload="WrapSys.CornerManager.previewBgLoad(this)" src="' + bgImgUrl + '">')
                imgBg.appendTo($("#cornerImgDiv"))
                var arrayObj = WrapSys.DynamicDiv.getMaterials();
                var selRow = $("#material_list").jqGrid("getGridParam", "selrow");
                var entity = getPageBean().findData("index", parseInt(selRow));
                var newArr = [];
                var tmp = null;

                $.each(entity.bindArr, function (i, element) {
                    tmp = arrayObj["key_" + element.id];
                    if (tmp != null) {
                        newArr.push({
                            x: parseInt(tmp.x * tmp.ratio),
                            y: parseInt(tmp.y * tmp.ratio),
                            w: Math.ceil(tmp.w * tmp.ratio),
                            h: Math.ceil(tmp.h * tmp.ratio),
                            url: element.url,
                            id: element.id });
                    }
                })

                var rectParams = null;
                $.each(newArr, function (i, element) {
                    rectParams = element.x + "|" + element.y + "|" + element.w + "|" + element.h;
                    $('<img class="preview_corner" onload="WrapSys.CornerManager.previewCornerLoad(this)" rect_params="' + rectParams + '" preview-corn-id="' + element.id + '"  src="' + element.url + '"  style="position: absolute;" />').appendTo($("#cornerImgDiv"));
                })
            }


            function getPicAdList(limitStart, limitEnd, readyToSend) {
                limitStart = parseInt(limitStart);
                limitEnd = parseInt(limitEnd);
                var ret = [];
                var singleData = null;
                var temp = null;
                var source = getPageBean().getSource();
                $.each(source, function (i, single) {
                    if (single.sTime < 0 || ( single.eTime != -1 && single.sTime > single.eTime )) {
                        return true;
                    }
                    if (single.sTime > limitEnd || (single.eTime != -1 && single.eTime < limitStart )) {
                        return true;
                    }
                    singleData = { start_id: single.sTime, end_id: single.eTime, head: "", end: ""}
                    $.each(single.bindArr, function (i, element) {
                        temp = $.extend({ }, singleData, {
                            x: parseInt(element.x * element.ratio),
                            y: parseInt(element.y * element.ratio),
                            w: Math.ceil(element.w * element.ratio),
                            h: Math.ceil(element.h * element.ratio),
                            uuid: element.id,
                            material_id: element.materialId
                        })
                        ret.push(temp)
                    })
                    if (readyToSend) {
                        single["readyToSend"] = true;
                    }
                })
                return ret;
            }

            function isValidCorner() {

            }

            function hasSelected() {
                var selRow = $("#material_list").jqGrid("getGridParam", "selrow");
                return selRow != null;
            }

            function setHighLight(entity) {
                $("label[corn-key]").click();
                $("label[corn-end-key]").click();
                if (entity != null) {
                    if (entity.sTime > -1) {
                        updateViewStart(entity)
                    }
                    if (entity.eTime > -1) {
                        updateViewEnd(entity)
                    }
                }
            }

            function checkNeedRemind(methodType, entity, handler) {
                var currentNum = $("#div_fragment_append").children().length;
                var needDlg = true;
                if (currentNum == 1) {
                    needDlg = false;
                } else {
                    var preDivTarget = $("div[fragment-line=" + (currentNum - 1) + "]");
                    var checkEnd = parseInt(preDivTarget.find("input:eq(1)").val());
                    needDlg = entity.sTime <= checkEnd;
                }
                if (!needDlg) {
                    handler();
                    return;
                }
                var remindInfo = null;
                if (methodType == "del") {
                    remindInfo = WrapSys.Config.REMIND_MSG_INFO.DEL_MATERIAL_INFO
                } else if (methodType == "modify") {
                    remindInfo = WrapSys.Config.REMIND_MSG_INFO.MODIFY_MATERIAL_INFO;
                }
                if (remindInfo != null) {
                    SystemDialog.queryConfirm(remindInfo, function (flag) {
                        if (flag == true) {
                            handler();
                        }
                    })
                }
            }

            function previewCornerLoad(element) {
                var curTarget = $(element);
                var rectParams = curTarget.attr("rect_params"); //xywh
                var rectArr = rectParams.split("|");
                curTarget.css({left: parseInt(rectArr[0]), top: parseInt(rectArr[1]), width: parseInt(rectArr[2]), height: parseInt(rectArr[3]) });
                console.log("preview_corner load complete id :" + curTarget.attr("preview-corn-id"))
            }

            function previewBgLoad(element) {
                $("#cornerImgDiv").css({ width: element.naturalWidth, height: element.naturalHeight });
                $(element).css({ width: element.naturalWidth, height: element.naturalHeight })
            }

            function doAccountRowRange() {
                var currentNum = $("#div_fragment_append").children().length;
                if (currentNum == 0) {
                    return;
                }
                var preDivTarget = null;
                var checkStart = -1;
                var checkEnd = -1;
                var frameArr = [];
                for (var i = 1; i < currentNum; i++) {
                    preDivTarget = $("div[fragment-line=" + i + "]");
                    checkStart = parseInt(preDivTarget.find("input:eq(0)").val());
                    checkEnd = parseInt(preDivTarget.find("input:eq(1)").val());
                    frameArr.push({ fragId: i, cStart: checkStart, eStart: checkEnd });
                }
                var source = getPageBean().getSource();
                var readyToUpdate = [];
                $.each(source, function (index, element) {
                    if (element.sTime == -1) {
                        return true;
                    }
                    element.range = [];
                    $.each(frameArr, function (index2, entity) {
                        if (entity.eStart >= element.sTime && (element.eTime == -1 || entity.cStart <= element.eTime  )) {
                            element.range.push(entity.fragId);
                        }
                    })
                    readyToUpdate.push(element);
                });
                $.each(readyToUpdate, function (index3, updateData) {
                    notifyUpdateCornerGrid(updateData)
                })
            }

            function findNoPositionDatas(limitStart, limitEnd) {
                var result = [];
                var temp = null;
                var source = getPageBean().getSource();
                $.each(source, function (i, single) {
                    if (single.sTime < 0 || ( single.eTime != -1 && single.sTime > single.eTime )) {
                        return true;
                    }
                    if (single.sTime > limitEnd || (single.eTime != -1 && single.eTime < limitStart )) {
                        return true;
                    }
                    $.each(single.bindArr, function (i, element) {
                        if (element.x == null) {
                            result.push("" + single.index)
                            return false;
                        }
                    })
                })
                return result;
            }

            function getNegativeOutpointList(limitEnd) {
                limitEnd = parseInt(limitEnd);
                var source = getPageBean().getSource();
                var ret = [];
                $.each(source, function (i, single) {
                    if (single.eTime == -1 && single.sTime <= limitEnd && single.sTime >= 0) {
                        ret.push(single.index);
                    }
                })
                return ret
            }

            function isDlgOpen() {
                return   $("#edit_corner-dlg").is(":visible");
            }

            return {
                addEntity: operator.add,
                addCornPic: addCornPic,
                clearEntity: operator.clear,
                delEntity: operator.del,
                recordStart: recordStart,
                recordEnd: recordEnd,
                getEntity: getEntity,
                getSource: getSource,
                openEditCornerDlg: openEditCornerDlg,
                initEditCornerDlg: initEditCornerDlg,
                readCornerObjPos: readCornerObjPos,
                getPicAdList: getPicAdList,
                isValidCorner: isValidCorner,
                setHighLight: setHighLight,
                hasSelected: hasSelected,
                previewCornerLoad: previewCornerLoad,
                previewBgLoad: previewBgLoad,
                doAccountRowRange: doAccountRowRange,
                findNoPositionDatas: findNoPositionDatas,
                getNegativeOutpointList: getNegativeOutpointList,
                isDlgOpen: isDlgOpen,
                getSelectEntity: getSelectEntity
            }
        })();
    }
);